package com.lsy.weizhi2.activity;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.google.gson.Gson;
import com.lsy.weizhi2.JsonObject.ActivityListObject;
import com.lsy.weizhi2.JsonObject.ReplyList;
import com.lsy.weizhi2.R;
import com.lsy.weizhi2.adapter.ActivityDetailAdapter2;
import com.lsy.weizhi2.adapter.FullyLinearLayoutManager;
import com.lsy.weizhi2.config.Constants;
import com.lsy.weizhi2.config.CostomFlag;
import com.lsy.weizhi2.config.MyHeight;
import com.lsy.weizhi2.config.MyInfo;
import com.lsy.weizhi2.customview.ActivityDetailUp;
import com.lsy.weizhi2.customview.MyListView;
import com.lsy.weizhi2.customview.ReplyDailog;
import com.lsy.weizhi2.customview.UserInfo;
import com.lsy.weizhi2.mybase.BaseApp;
import com.lsy.weizhi2.mybase.MyBaseActivity;
import com.lsy.weizhi2.mybase.MyTitleView;
import com.lsy.weizhi2.mysql.MySQLOperate;
import com.lsy.weizhi2.myutils.ReplyDailogCall;
import com.lsy.weizhi2.myutils.UserInfoCall;
import com.lsy.weizhi2.utils.MyMethod;
import com.lsy.weizhi2.utils.MyOkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ActivityDetail2 extends MyBaseActivity implements View.OnClickListener{
    private Context context;
    private MyTitleView activity_detail;
    private UserInfo activity_detail_user_info;
    private TextView activity_detail_title,activity_detail_image_num,activity_detail_content,
            activity_detail_baoming_num,activity_detail_reply_num,activity_detail_look_num,
            activity_detail_baoming;
    private ViewPager activity_detail_vp;
    private RecyclerView reply_rv;
    private ActivityDetailAdapter2 activityDetailAdapter;
    private ReplyDailog reply_dialog;
    private RelativeLayout gengduo_rl,activity_detail_gallery;
    private int xx,pageNo;
    private Handler handler = new Handler();
    private boolean isload;

    private ActivityListObject.ListBean bean;
    private Gson gson;
    private ReplyList replyList;
    private List<ReplyList.ListBean> list_r;

    private int size;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail2);
        context=ActivityDetail2.this;
        findView();
    }

    private void findView() {
        gson = new Gson();
        list_r = new ArrayList<>();
        String json = getIntent().getStringExtra("json");
        if (json != null) {
            bean = gson.fromJson(json, ActivityListObject.ListBean.class);
        } else {
            bean = MySQLOperate.getInstance(context).Select_Activity(CostomFlag.Activity_Flag);
        }
        activity_detail= (MyTitleView) findViewById(R.id.activity_detail);
        activity_detail_user_info= (UserInfo) findViewById(R.id.activity_detail_user_info);
        activity_detail_title= (TextView) findViewById(R.id.activity_detail_title);
        activity_detail_image_num= (TextView) findViewById(R.id.activity_detail_image_num);
        activity_detail_content= (TextView) findViewById(R.id.activity_detail_content);
        activity_detail_baoming_num= (TextView) findViewById(R.id.activity_detail_baoming_num);
        activity_detail_reply_num= (TextView) findViewById(R.id.activity_detail_reply_num);
        activity_detail_look_num= (TextView) findViewById(R.id.activity_detail_look_num);
        activity_detail_baoming= (TextView) findViewById(R.id.activity_detail_baoming);
        activity_detail_vp= (ViewPager) findViewById(R.id.activity_detail_vp);
        reply_rv= (RecyclerView) findViewById(R.id.reply_rv);
        reply_dialog= (ReplyDailog) findViewById(R.id.reply_dialog);
        gengduo_rl= (RelativeLayout) findViewById(R.id.gengduo_rl);
        activity_detail_gallery= (RelativeLayout) findViewById(R.id.activity_detail_gallery);
        FullyLinearLayoutManager manager=new FullyLinearLayoutManager(context);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        reply_rv.setLayoutManager(manager);
        reply_rv.setNestedScrollingEnabled(false);
        activityDetailAdapter = new ActivityDetailAdapter2(context,bean);
        reply_rv.setAdapter(activityDetailAdapter);
        gengduo_rl.setOnClickListener(this);
        activity_detail_baoming.setOnClickListener(this);
        setData();
    }

    private void setData() {
        activity_detail_user_info.setContent(bean.getRealName(),bean.getAvatar(),"收藏");
        activity_detail_title.setText(bean.getTitle());
        activity_detail_baoming_num.setText(bean.getEnrollment()+"");
        String str1=bean.getContent();
        Spanned content= Html.fromHtml(str1);
        activity_detail_content.setText(content);
        String str=bean.getPhoto();
        if(str!=null&&str.length()!=0){
            String[]strs=str.split(",");
            setActivityImages(strs);
        }
    }

    /**
     * 活动图片加载
     */
    public void setActivityImages(String[]str) {
        //设置ViewPager的布局
        Log.i("NoteDetailUp", "SCREEN_HEIGHT==" + BaseApp.REAL_HEIGHT);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                BaseApp.SCREEN_WIDTH * 5 / 10, BaseApp.REAL_HEIGHT * 380 / 1334);
        Log.i("NoteDetailUp", "height==" + params.height);
        /**** 重要部分  ******/
        //clipChild用来定义他的子控件是否要在他应有的边界内进行绘制。 默认情况下，clipChild被设置为true。 也就是不允许进行扩展绘制。
        activity_detail_vp.setClipChildren(false);
        //父容器一定要设置这个，否则看不出效果
        activity_detail_gallery.setClipChildren(false);

        if(str!=null){
            size=str.length;
            activity_detail_image_num.setText("1/"+size);

        }
        activity_detail_vp.setLayoutParams(params);
        //为ViewPager设置PagerAdapter
        activity_detail_vp.setAdapter(new MyPagerAdapter(str));
        //设置ViewPager切换效果，即实现画廊效果
        activity_detail_vp.setPageTransformer(true, new ZoomOutPageTransformer());
        //设置预加载数量
        activity_detail_vp.setOffscreenPageLimit(2);
        //设置每页之间的左右间隔
        Log.i("NoteDetailUp", "SCREEN_WIDTH==" + BaseApp.SCREEN_WIDTH);
        activity_detail_vp.setPageMargin(BaseApp.SCREEN_WIDTH * 10 / 750);
        activity_detail_vp.addOnPageChangeListener(new MyOnPageChangeListener());
        //将容器的触摸事件反馈给ViewPager
        activity_detail_gallery.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // dispatch the events to the ViewPager, to solve the problem that we can swipe only the middle view.
                return activity_detail_vp.dispatchTouchEvent(event);
            }

        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        xx = 0;
        ViewTreeObserver vto = activity_detail.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (xx < 1) {
                    xx++;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(activity_detail.getLayoutParams());
                            params.height = MyHeight.ACTIONBAR + MyHeight.MyTitleHeight;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                activity_detail.setLayoutParams(params);
                            }
                        }
                    });
                }
            }
        });
        reply_rv.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                boolean bottom=recyclerView.canScrollVertically(-1);
                if(newState==RecyclerView.SCROLL_STATE_SETTLING&&!bottom&&!isload){
                    activityDetailAdapter.UpData(list_r, 1, 0);
                    isload=true;
                }else if(newState==RecyclerView.SCROLL_STATE_IDLE&&!bottom&&isload){

                    if(pageNo>=1&&list_r!=null&&list_r.size()>=10*pageNo){
                        activityDetailAdapter.UpData(list_r, 1, 1);
                        pageNo++;
                        getReplyList();
                    }else{
                        activityDetailAdapter.UpData(list_r, 1, 2);
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                activityDetailAdapter.UpData(list_r, 0, 0);
                            }
                        },500);
                    }

                }
            }
        });
        //回复窗口回调
        reply_dialog.setReplyDailogCall(new ReplyDailogCall() {
            @Override
            public void onClick(View view, int flag) {
                switch (flag){
                    case ReplyDailogCall.OK:
                        String content=reply_dialog.getText().toString();
                        ReceiveActivity(bean.getId()+"",content);
                        reply_dialog.setVisibility(View.GONE);
                        break;
                    case ReplyDailogCall.CANCEL:
                        reply_dialog.setVisibility(View.GONE);
                        break;
                }
            }
        });
        activity_detail_user_info.setUserInfoCall(new UserInfoCall() {
            @Override
            public void onClick(View view, int flag) {
                switch (flag){
                    case UserInfoCall.FOLLOW:
                        //调用活动收藏接口
                        ShouCang2();
                        break;
                    case UserInfoCall.IMAGE:
                        //跳转用户信息界面
                        break;
                }
            }
        });
        pageNo=1;
        getReplyList();
    }

    /**
     * 收藏活动
     */
    private void ShouCang2(){
        MyOkHttpUtils.getInstance(context).doPost(Constants.ShouCang2+bean.getId(),null)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        if(message!=null){
                            try {
                                JSONObject jsonObject=new JSONObject(message);
                                boolean resutl=jsonObject.getBoolean("result");
                                if(resutl){
                                    MyMethod.ShowDialog(context,"收藏成功");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    /**
     * 获取回复详情
     */
    private void getReplyList() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNo", pageNo + "");
        map.put("pageSize", "10");
        MyOkHttpUtils.getInstance(context).doGet(Constants.SELECT_ACTIVTY_REPLY + bean.getId() + "/reply", map)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        Log.i("ActivityDetail2", "message====222222===" + message);
                        replyList = gson.fromJson(message, ReplyList.class);
                        if (pageNo == 1) {
                            list_r.clear();
                        }
                        List<ReplyList.ListBean> list = replyList.getList();
                        if (list != null && list.size() != 0) {
                            list_r.addAll(list);
                            activityDetailAdapter.UpData(list_r, 0, 0);
                        } else {
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    activityDetailAdapter.UpData(list_r,0,0);
                                }
                            },1000);
                        }

                    }
                });
    }

    @Override
    public void onPause() {
        super.onPause();
        xx = 0;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.activity_detail_gengduo:
                reply_dialog.setVisibility(View.VISIBLE);
                break;
            case R.id.activity_detail_baoming:
                BaoMing();
                break;
        }
    }

    /**
     * 回复活动
     * @param activity_id
     * @param content
     */
    private void ReceiveActivity(String activity_id, String content) {
        Map<String, String> map = new HashMap<>();
        map.put("activityId", activity_id);
        map.put("content", content);
        MyOkHttpUtils.getInstance(context).doPost(Constants.RECEIVE_ACTIVITY, map)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        Log.i("ActivityDetail", "message=receive=" + message);
                        pageNo=1;
                        getReplyList();
                    }
                });
    }

    /**
     * 报名接口
     */
    private void BaoMing(){
        MyOkHttpUtils.getInstance(context).doPost(Constants.ActivityBaoMing+bean.getId()+"/registration",null)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        if(message!=null){
                            try {
                                JSONObject jsonObject=new JSONObject(message);
                                boolean result=jsonObject.getBoolean("result");
                                if(result){
                                    MyMethod.ShowDialog(context,"报名成功");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    class MyPagerAdapter extends PagerAdapter {
        private String[] str;

        public MyPagerAdapter(String[] str) {
            this.str = str;
        }

        @Override
        public int getCount() {
            //return viewList==null?0:viewList.size();
            return str==null?6:str.length;//ViewPager里的个数
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return (view == object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            if(str==null){
                imageView.setImageResource(R.mipmap.note_image);
            }else{
                Glide.with(context)
                        .load(new GlideUrl(Constants.DOWN_USER_PICTURE+str[position],new LazyHeaders.Builder().addHeader("WZ-AUTH-TOKEN", MyInfo.Token).addHeader("WZ-AUTH-ID",MyInfo.User_Id+"").build()))
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(imageView);
            }
            ((ViewPager) container).addView(imageView);
            return imageView;

        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((ImageView) object);
        }
    }

    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageSelected(int position) {
            //这里做切换ViewPager时，底部RadioButton的操作
            activity_detail_image_num.setText(position + 1 + "/"+size);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            if (activity_detail_gallery != null) {
                activity_detail_gallery.invalidate();
            }
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    }

    /**
     * 实现的原理是，在当前显示页面放大至原来的MAX_SCALE
     * 其他页面才是正常的的大小MIN_SCALE
     */
    class ZoomOutPageTransformer implements ViewPager.PageTransformer {
        private static final float MAX_SCALE = 1.2f;
        private static final float MIN_SCALE = 0.8f;//0.85f

        @Override
        public void transformPage(View view, float position) {
            //setScaleY只支持api11以上
            if (position < -1) {
                view.setScaleX(MIN_SCALE);
                view.setScaleY(MIN_SCALE);
            } else if (position <= 1) //a页滑动至b页 ； a页从 0.0 -1 ；b页从1 ~ 0.0
            { // [-1,1]
//              Log.e("TAG", view + " , " + position + "");
                float scaleFactor = MIN_SCALE + (1 - Math.abs(position)) * (MAX_SCALE - MIN_SCALE);
                view.setScaleX(scaleFactor);
                //每次滑动后进行微小的移动目的是为了防止在三星的某些手机上出现两边的页面为显示的情况
                if (position > 0) {
                    view.setTranslationX(-scaleFactor * 2);
                } else if (position < 0) {
                    view.setTranslationX(scaleFactor * 2);
                }
                view.setScaleY(scaleFactor);

            } else { // (1,+Infinity]

                view.setScaleX(MIN_SCALE);
                view.setScaleY(MIN_SCALE);

            }
        }

    }
}
